<template>
    <form-container v-if="showPage" :right-tabs="['优惠券详情页', '优惠券列表页']">
        <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm" label-width="150px" class="pv20 ph15" style="min-width: 660px;">
            <el-form-item label="券用途" required>
                <div v-for="row in radioPurpose" :key="row.value" class="f-c f-warp mr15">
                    <el-radio-group :disabled="activityDisabled" v-model="ruleForm.purpose" @change="radioChangePurpose">
                        <el-radio :value="row.value">{{ row.label }}</el-radio>
                    </el-radio-group>
                    <div v-if="row.value === radioPurposeParaphrase.saoMaFaQuan" class="f-c">
                        <span class="ph5">(</span>
                        <el-radio-group :disabled="activityDisabled || ruleForm.purpose !== radioPurposeParaphrase.saoMaFaQuan" v-model="ruleForm.sub_type">
                            <el-radio v-for="row in couponScanCodeSubTypes" :key="row.value" :value="row.value" class="mr15">{{ row.label }}</el-radio>
                        </el-radio-group>
                        <span class="ph5">)</span>
                    </div>
                </div>
            </el-form-item>
            <el-form-item :label="isParkCoupon ? '停车券头图' : '优惠券图'" prop="head_img">
                <div>
                    <p class="form-tip-color fz11">*建议图片尺寸：750x750dpi，不超过2M 支持{{ defaultImageType }}格式</p>
                </div>
            </el-form-item>
            <el-form-item label="优惠券标题" prop="name">
                <div>
                    <GInputTrimStart
                        id="name"
                        v-model="ruleForm.name"
                        show-word-limit
                        :maxlength="30"
                        :placeholder="`请输入${isParkCoupon ? '停车' : '优惠'}券标题`"
                        clearable
                        class="w250"
                    />
                    <p class="form-tip-color fz11">*建议出现品牌及活动亮点，如"优衣库满300减50"</p>
                </div>
            </el-form-item>
            <!--闪购优惠券-->
            <div v-if="isFlashCoupon">
                <el-form-item label="副标题(选填)">
                    <div>
                        <GInputTrimStart
                            v-model="ruleForm.subhead"
                            show-word-limit
                            :maxlength="12"
                            placeholder="请输入副标题"
                            clearable
                            class="w250"
                        />
                        <p class="form-tip-color fz11">*建议说明活动主题，如"换季换新衣给全家最舒适的"</p>
                    </div>
                </el-form-item>
                <el-form-item v-if="showFormItem.campaigns" label="优惠券所属活动">
                    <div v-if="ruleForm.campaign_id">
                        <el-text>{{ ruleForm.campaignConfig.name }}</el-text>
                        <el-text v-if="!activityDisabled">
                            <el-text type="primary" ml15 pointer @click="showCampaignDialog">更换</el-text>
                            <el-text type="danger" ml15 pointer @click="removeCampaign">删除</el-text>
                        </el-text>
                    </div>
                    <el-button v-else :disabled="activityDisabled" type="primary" @click="showCampaignDialog">选择活动</el-button>
                </el-form-item>
                <el-form-item label="适用范围" prop="channel">
                    <div>
                        <el-radio-group :disabled="activityDisabled" v-model="ruleForm.channel" @change="radioChangeChannel">
                            <el-radio v-for="row in couponChannel" :key="row.value" :value="row.value">{{ row.label }}</el-radio>
                        </el-radio-group>
                        <p class="form-tip-color fz11">*线上优惠券仅适用于闪购商品</p>
                    </div>
                </el-form-item>
                <el-form-item v-if="ruleForm.channel" label="券类型" :class="{'mb8': !!ruleForm.soule}" required>
                    <div>
                        <el-radio-group :disabled="activityDisabled" v-model="ruleForm.soule" @change="radioChangeTypes">
                            <el-radio v-for="row in couponTypes" :key="row.value" :value="row.value">{{ row.label }}</el-radio>
                        </el-radio-group>
                        <p class="form-tip-color fz11">{{ typesTips[ruleForm.soule] }}</p>
                    </div>
                </el-form-item>
                <!--满减券-->
                <el-form-item v-if="ruleForm.soule === couponTypesParaphrase.manJian" prop="typeValue">
                    <span class="pr8">满</span>
                    <GInputNumber v-model="ruleForm.over" :disabled="activityDisabled" type="decimal" decimal="2" clearable width="80px"/>
                    <span class="ph8">减</span>
                    <GInputNumber v-model="ruleForm.minus" :disabled="activityDisabled" type="decimal" decimal="2" clearable width="80px"/>
                </el-form-item>
                <!--折扣券-->
                <el-form-item v-if="ruleForm.soule === couponTypesParaphrase.zheKou" prop="typeValue">
                    <span class="pr8">购买</span>
                    <GInputNumber v-model="ruleForm.purchase" :disabled="activityDisabled" type="integer" clearable width="80px"/>
                    <span class="ph8">件，打</span>
                    <GInputNumber v-model="ruleForm.off" :disabled="activityDisabled" type="decimal" decimal="1" max="10.0" clearable width="80px"/>
                    <span class="pl8">折</span>
                </el-form-item>
                <!--礼品券-->
                <el-form-item v-if="ruleForm.soule === couponTypesParaphrase.liPin" prop="typeValue">
                    <el-input :disabled="activityDisabled" v-model="ruleForm.demand" :maxlength="6" clearable show-word-limit class="w150" placeholder="请输入"/>
                </el-form-item>
                <!--现金券-->
                <div v-if="isCashCoupon">
                    <el-form-item prop="typeValue">
                        <GInputNumber v-model="ruleForm.minus" :disabled="activityDisabled" type="decimal" decimal="2" clearable width="80px"/>
                        <span class="ph8">元&nbsp;/</span>
                        <el-input :disabled="activityDisabled" v-model="ruleForm.demand" :maxlength="6" clearable show-word-limit class="w145" placeholder="请输入"/>
                    </el-form-item>
                    <div class="f-c">
                        <el-form-item label="使用门槛" :required="!!ruleForm.amount_limit">
                            <el-switch v-model="ruleForm.amount_limit" :active-value="1" :inactive-value="0" @change="switchAmountLimit"/>
                        </el-form-item>
                        <el-form-item v-if="ruleForm.amount_limit" label-width="0">
                            <span class="ph8">满</span>
                            <el-form-item label-width="0" prop="amount_over">
                                <GInputNumber v-model="ruleForm.amount_over" type="decimal" decimal="2" :maxlength="7" clearable width="90px"/>
                                <span class="pl8">元可使用 1 张</span>
                            </el-form-item>
                        </el-form-item>
                        <el-form-item v-else label-width="0">
                            <span class="pl8">不设限</span>
                        </el-form-item>
                    </div>
                    <div class="f-c">
                        <el-form-item label="单笔订单使用上限" :required="!!ruleForm.use_limit">
                            <el-switch v-if="!isOnLineCoupon" v-model="ruleForm.use_limit" :active-value="1" :inactive-value="0" @change="switchUseLimitNum"/>
                        </el-form-item>
                        <el-form-item v-if="isOnLineCoupon" label-width="0">单笔订单最多使用1张</el-form-item>
                        <el-form-item v-else-if="ruleForm.use_limit" label-width="0">
                            <p class="ph8">
                                <span v-if="!isOfflineCoupon">线下</span><!--线上线下 显示-->
                                <span>单笔订单最多使用</span><!--线下/线上线下 显示-->
                            </p>
                            <el-form-item label-width="0" prop="use_limit_num">
                                <!--线下/线上线下 显示-->
                                <GInputNumber v-model="ruleForm.use_limit_num" type="integer" clearable :maxlength="7" width="90px"/>
                                <span class="pl8">张</span>
                                <!--线上线下-->
                                <span v-if="!isOfflineCoupon">，线上单笔订单最多使用 1 张</span>
                            </el-form-item>
                        </el-form-item>
                        <el-form-item v-else label-width="0">
                            <span class="pl8">{{ isOfflineCoupon ? '不设限' : '线下单笔订单不设限，线上单笔订单最多使用 1 张' }}</span>
                        </el-form-item>
                    </div>
                </div>
                <!--抵用券-->
                <el-form-item v-if="ruleForm.soule === couponTypesParaphrase.diYong" prop="typeValue">
                    <GInputNumber v-model="ruleForm.arrive" :disabled="activityDisabled" type="decimal" decimal="2" clearable width="80px"/>
                    <span class="ph8">元&nbsp;/可抵</span>
                    <GInputNumber v-model="ruleForm.over" :disabled="activityDisabled" type="decimal" decimal="2" clearable width="80px"/>
                    <span class="ph8">元</span>
                </el-form-item>
            </div>
            <!--停车券优惠券-->
            <div v-if="isParkCoupon">
                <el-form-item label="券类型" prop="soule" :class="{'mb8': !!ruleForm.soule}" required>
                    <div>
                        <el-radio-group :disabled="activityDisabled" v-model="ruleForm.soule" @change="radioChangeTypes">
                            <el-radio v-for="row in parkCouponTypes" :key="row.value" :value="row.value">{{ row.label }}</el-radio>
                        </el-radio-group>
                        <p class="form-tip-color fz11">{{ parkTypesTips[ruleForm.soule] }}</p>
                    </div>
                </el-form-item>
                <!--折扣券-->
                <el-form-item v-if="ruleForm.soule === couponTypesParaphrase.zheKou" prop="typeValue">
                    <span class="pr8">支付时享受</span>
                    <GInputNumber v-model="ruleForm.off" :disabled="activityDisabled" type="decimal" decimal="1" max="10.0" clearable width="80px"/>
                    <span class="pl8">折</span>
                </el-form-item>
                <!--现金券-->
                <el-form-item v-if="isCashCoupon" prop="typeValue">
                    <span class="pr8">抵扣停车费</span>
                    <GInputNumber v-model="ruleForm.minus" :disabled="activityDisabled" type="decimal" decimal="2" clearable width="80px"/>
                    <span class="pl8">元</span>
                </el-form-item>
                <!--时长券-->
                <el-form-item v-if="ruleForm.soule === couponTypesParaphrase.shiChang" prop="typeValue">
                    <span class="pr8">停车</span>
                    <GInputNumber v-model="ruleForm.free_park_hour" :disabled="activityDisabled" type="integer" clearable width="80px"/>
                    <span class="pl8">小时内免费</span>
                </el-form-item>
            </div>
            <!--有效期-->
            <ValidPeriod
                radioText="领取"
                validPeriodText="领取优惠券"
                :disabledStart="activityDisabled"
                :ruleForm="ruleForm"
                :disabled-date="disabledDate"
                @change="changeDateRangeValidPeriod"
            />
            <!--会员领取权限-->
            <BuyLimit
                v-if="showFormItem.buyLimit"
                obtainText="领取"
                :ruleForm="ruleForm"
                :levelOptions="levelOptions"
                :memberGroupOptions="memberGroupOptions"
                @update-member="getMemberGroups"
                @change="changeBuyLimit"
            />
            <!--是否限领-->
            <div v-if="showFormItem.receiveRule">
                <el-form-item label="是否限领" :required="ruleForm.receiveRule" :class="{'mb12': !!ruleForm.receiveRule}">
                    <el-switch v-model="ruleForm.receiveRule" @change="switchReceiveRule"/>
                    <span class="form-tip-color fz11 pl15">*如需对消费者领取优惠券有数量限制，请打开此选项</span>
                </el-form-item>
                <div v-if="ruleForm.receiveRule" class="f-c">
                    <el-form-item>
                        <el-select v-model="ruleForm.receive_rule" class="w120">
                            <el-option v-for="row in receiveRuleOptions" :key="row.value" :value="row.value" :label="row.label"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="ruleForm.receiveRule" prop="receive_limit" label-width="8px">
                        <GInputNumber v-model="ruleForm.receive_limit" type="upInteger" :maxlength="9" clearable width="80px" @input="getReceiveText"/>
                        <span class="pl8">张</span>
                    </el-form-item>
                </div>
            </div>

            <!--店铺券-->
            <div v-if="isShopCoupon">
                <el-form-item label="选择店铺" prop="groupIds" :rules="rules.groupName">
                    <el-select
                        v-model="ruleForm.groupIds"
                        :disabled="activityDisabled"
                        clearable filterable
                        placeholder="请选择店铺"
                        class="w250"
                        @change="changeSelectShop"
                    >
                        <el-option
                            v-for="row in shopListData"
                            :key="row.id"
                            :value="row.id"
                            :label="row.name"
                        />
                    </el-select>
                </el-form-item>
                <div v-if="showAllItems">
                    <el-form-item label="选择商品" prop="all_item" :class="{'mb8': ruleForm.all_item === 0}">
                        <el-radio-group v-model="ruleForm.all_item" :disabled="activityDisabled" @change="changeAllItems">
                            <el-radio :value="0">选择店内商品</el-radio>
                            <el-radio :value="1">全部商品（包含未来店铺内新增商品）</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item v-if="ruleForm.all_item === 0" prop="itemName" :rules="rules.all_item">
                        <el-input
                            v-model="ruleForm.itemName"
                            readonly
                            placeholder="请选择适用商品"
                            @click="showItemDialog"
                            id="itemName"
                            class="w250"
                        >
                            <template #suffix>
                                <el-icon v-if="ruleForm.item_ids.length" :size="14" pointer @click="clearItems">
                                    <CircleClose/>
                                </el-icon>
                            </template>
                        </el-input>
                    </el-form-item>
                </div>
                <div v-if="showFormItem.sendShop">
                    <el-form-item label="自定义发券权限" :required="ruleForm.sendable === 1" :class="{'mb8': ruleForm.sendable === 1}">
                        <el-switch v-model="ruleForm.sendable" :active-value="1" :inactive-value="0" @change="switchSendAble"/>
                        <span class="form-tip-color fz11 pl15">*未打开开关仅服务台有发券权限，打开开关可自定义发券权限</span>
                    </el-form-item>
                    <el-form-item v-if="ruleForm.sendable === 1" prop="sendShopName">
                        <el-input
                            v-model="ruleForm.sendShopName"
                            readonly
                            placeholder="请选择可发券店铺"
                            @click="showSendShopDialog"
                            id="sendShopName"
                            class="w250"
                        >
                            <template #suffix>
                                <el-icon v-if="ruleForm.send_shop_ids.length" :size="14" pointer @click="clearShops(sendShopKeyName)">
                                    <CircleClose/>
                                </el-icon>
                            </template>
                        </el-input>
                    </el-form-item>
                </div>
            </div>
            <div v-else>
                <el-form-item v-if="isFlashCoupon" label="选择店铺" prop="groupName">
                    <el-input
                        v-model="ruleForm.groupName"
                        readonly
                        placeholder="请选择店铺"
                        @click="showGroupShopDialog"
                        id="groupName"
                        class="w250"
                    >
                        <template #suffix>
                            <el-icon v-if="ruleForm.group_ids.length" :size="14" pointer @click="clearShops(groupShopKeyName)">
                                <CircleClose/>
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
            </div>

            <el-form-item label="使用须知" prop="describe">
                <el-input
                    id="describe"
                    v-model="ruleForm.describe"
                    show-word-limit
                    placeholder="请输入使用须知"
                    type="textarea"
                    :maxlength="1000"
                    :rows="6"
                    class="w250"
                />
            </el-form-item>

            <div v-if="isFlashCoupon">
                <el-form-item v-if="ruleForm.channel" label="使用优惠的订单" prop="item_refundable">
                    <el-radio-group :disabled="activityDisabled" v-model="ruleForm.item_refundable" @change="changeItemRefundable">
                        <el-radio :value="1">{{ isOnLineCoupon ? '可单件退' : '可退' }}</el-radio>
                        <el-radio :value="0">不可退</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item v-if="ruleForm.item_refundable === 1" label="使用优惠的订单全退后" prop="coupon_refundable">
                    <el-radio-group :disabled="activityDisabled" v-model="ruleForm.coupon_refundable">
                        <el-radio :value="0">优惠券不退回</el-radio>
                        <el-radio :value="1">优惠券退回券包</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="优惠券详情图(选填)">
                    <div>
                        <p class="form-tip-color fz11 line-h20">
                            *建议图片尺寸：宽度750dpi，高度不限，支持{{ defaultImageType }}格式<br/>
                            *最多支持20张图片，单张图片不超过2M，支持一次上传多张图片<br/>
                            *支持拖动图片排序
                        </p>
                    </div>
                </el-form-item>
            </div>

            <div v-if="showFormItem.sendWay" :class="{'f-c': showFormItem.sustain}">
                <el-form-item label="发放方式" prop="timesRadio" :class="{'mb12': ruleForm.timesRadio && !showFormItem.sustain}">
                    <el-radio-group :disabled="activityDisabled" v-model="ruleForm.timesRadio" @change="changeTimesRadio">
                        <el-radio :value="1">持续发放</el-radio>
                        <el-radio v-if="!showFormItem.sustain" :value="2">多时段发放</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item
                    v-if="ruleForm.timesRadio"
                    :label-width="showFormItem.sustain ? '0' : ''"
                    :label="!showFormItem.sustain ? (ruleForm.timesRadio === 1 ? '发放时间' : '分发时段') : ''"
                    required mb0
                >
                    <div style="position: relative;">
                        <p v-if="isEdit && !showFormItem.sustain" style="position: absolute;top: -24px;left: 318px;">剩余库存</p>
                        <div v-for="(row,i) in ruleForm.times" class="f-c mb18">
                            <el-form-item
                                v-if="!showFormItem.sustain"
                                :key="row.key"
                                :prop="'times.' + i + '.date'"
                                :rules="[{
                                    required: true,
                                    validator: (rule: ObjValueAny, value: string[], callback: Function) => validatorTimesDate(rule, value, callback, i),
                                    trigger: 'change'
                                }]"
                            >
                                <FormRangeDate v-model="row.date" :dis-start="row.disStart" :disabled="row.disabled" :disabled-date="row.disabledDate"/>
                            </el-form-item>

                            <el-form-item
                                label-width="8"
                                :key="row.key"
                                :prop="'times.' + i + '.editNum'"
                                :rules="[{
                                    required: true,
                                    validator: (rule: ObjValueAny, value: number, callback: Function) => validatorTimesNum(rule, value, callback, i),
                                    trigger: 'change'
                                }]"
                            >
                                <GInputNumber :disabled="row.disabled" v-model="row.editNum" :maxlength="9" clearable width="70px" placeholder="请输入"/>
                                <span class="pl8">张</span>
                                <div v-if="ruleForm.timesRadio === 2" class="f-c">
                                    <el-icon v-if="ruleForm.times.length - 1 === i" @click="addTimes" class="circle-plus-filled-icon fz16 ml10">
                                        <CirclePlusFilled/>
                                    </el-icon>
                                    <el-icon v-if="ruleForm.times.length > 1 && !row.hideRemove" @click="removeTimes(i)" class="remove-filled-icon fz16 ml10">
                                        <RemoveFilled/>
                                    </el-icon>
                                </div>
                            </el-form-item>
                        </div>
                    </div>
                </el-form-item>
            </div>

            <el-form-item v-if="showFormItem.advanceNotice" label="预热时间(选填)">
                <LotteryPeriod v-model="ruleForm.advanceNotice" label="发放开始前"/>
            </el-form-item>

            <el-form-item v-if="isFlashCoupon" label="优惠补贴比例" class="mb22">
                <span class="pr6">商场补贴</span>
                <el-form-item prop="mall_subsidy_rate">
                    <GInputNumber
                        :disabled="activityDisabled"
                        v-model="ruleForm.mall_subsidy_rate"
                        id="mall_subsidy_rate"
                        type="decimal"
                        decimal="1"
                        :max="100"
                        clearable
                        width="80px"
                    />
                    <span class="pl6">%&nbsp;&nbsp;&nbsp;店铺补贴 {{ shopSubsidyRate }}%</span>
                </el-form-item>
            </el-form-item>

            <el-form-item label="备注(选填)" class="mb0">
                <div>
                    <el-input
                        v-model="ruleForm.remark"
                        show-word-limit
                        maxlength="100"
                        placeholder="请输入备注"
                        type="textarea"
                        :rows="6"
                        class="w250"
                    />
                    <p class="form-tip-color fz11">*仅商场{{ isFlashCoupon ? '和店铺' : '' }}可见</p>
                </div>
            </el-form-item>
        </el-form>

        <template #right="{ active }">
            <div class="pv15 f-d-c">
                <el-scrollbar v-if="active === 0" style="width: 300px;height: 600px;background-color: #FFFFFF;">
                    <div>{{ ruleForm.shopLogo }}</div>
                    <div>{{ ruleForm.shopName }}</div>
                    <div>{{ ruleForm.shopAddress }}</div>
                    <div v-for="row in 100" style="color: #141414;">{{ row }}优惠券详情页</div>
                </el-scrollbar>
                <div v-if="active === 1">优惠券列表页</div>
            </div>
        </template>

        <template #footer>
            <el-button
                type="primary"
                size="default"
                class="fz13 w120"
                :loading="subLoading"
                :disabled="subLoading"
                @click="submitForm(ruleFormRef)"
            >
                保存
            </el-button>
            <el-button type="info" size="default" class="fz13 w120" @click="goBack">取消</el-button>
        </template>
    </form-container>

    <!--优惠券所属活动-->
    <RadioCampaign v-model="ruleForm.campaign_id" v-model:dialog="campaignDialog" @change="changeCampaign"/>
    <!--选择店铺-->
    <CheckShop ref="ShopModelRef" v-model="shopDialog" :ids="storeShopIds" :key-name="shopKeyName" @change="changeShops"/>
    <!--选择商品-->
    <CheckItem ref="ItemModelRef" v-model="itemDialog" :ids="ruleForm.item_ids" :params="{ shop_id: ruleForm.groupIds }" @change="changeItems"/>
    <!--返回上一页-->
    <PreventBack ref="PreventBackRef"/>

    <el-dialog v-model="dialogPrompt" :close-on-click-modal="false" title="温馨提示" width="420px">
        <div text-c style="padding: 5px 10px 10px;">
            <div class="pb8">保存后已领取的券会同步变更（已失效的券不改变状态）</div>
            <div>确认保存吗？</div>
        </div>
        <template #footer>
            <el-button @click="closeDialogPrompt">取消</el-button>
            <el-button type="primary" @click="onSave">确认</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { reactive, ref, nextTick, toRefs, computed, onMounted } from "vue";
    import { ElMessage } from "element-plus";
    import { CirclePlusFilled, RemoveFilled, CircleClose } from "@element-plus/icons-vue";
    import { useRoute, useRouter } from "vue-router";

    import FormContainer from "@/components/form/FormContainer.vue";
    import ValidPeriod from "@/components/form/ValidPeriod.vue";// 有效期
    import BuyLimit from "@/components/form/BuyLimit.vue";// 会员领取权限
    import FormRangeDate from "@/components/form/FormRangeDate.vue";// 范围日期选择组件
    import LotteryPeriod from "@/components/form/LotteryPeriod.vue";// 预热时间
    import RadioCampaign from "@/components/checkDialog/RadioCampaign.vue";// 选择活动
    import CheckShop from "@/components/checkDialog/CheckShop.vue";// 选择店铺
    import CheckItem from "@/components/checkDialog/CheckItem.vue";// 选择商品
    import PreventBack from "@/components/form/PreventBack.vue";// 返回上一页

    import { getShowFormItem } from "@/views/MarketingCenter/CouponManage/FlashCoupon/handler";
    import { isFlashCouponGroupId, isParkCouponGroupId, isOriginShopCoupon } from "@/utils/globalTypes";
    import { _layoutStore, _mallStore, _ossStore, _userStore } from "@/store/config";
    import useLoading from "@/hooks/loading";
    import { getRestfulMallV2CouponDetail, getApiShopDetail } from "@/assets/api";
    import { getRestfulMallLevelsFilter, getRestfulMallMemberGroupsFilter } from "@/assets/api/handler";
    import { TypeFilters } from "@/interface/filters";
    import { getExcludeFilters, getFiltersDictParaphrase } from "@/filters/utils";
    import { CouponPurpose } from "@/filters/data";
    import {
        FCouponScanCodeSubTypes,
        FCouponChannel, FCouponChannelParaphrase,
        FCouponTypes, FParkCouponTypes, FCouponTypesParaphrase,
        FReceiveRules, FReceiveRulesLabel,
    } from "@/filters";
    import { validatorDateRangeRule, validatorValidPeriodRule } from "@/components/globalUtils/ValidPeriod";
    import { getCouponValidPeriodDetail } from "@/components/formUtils/ValidPeriod";
    import { getBuyLimitRuleForm, buyLimitLevelLimitRule, buyLimitLevelIdsRule, buyLimitDenyGroupsRule, resetBuyLimit } from "@/components/formUtils/BuyLimit";
    import { disBeforeDay, getDateParse, getLotteryPeriod } from "@/utils/time.ts";

    const route = useRoute();
    const router = useRouter();
    const { showLoading, hideLoading } = useLoading();// 加载loading

    // 返回上一页
    const PreventBackRef = ref();
    const goBack = () => {
        router.back();
    }

    const { defaultImageType } = toRefs(_ossStore);// 上传图片默认类型
    const { isSuperManage } = toRefs(_userStore);// 超级管理员
    const routeParams: ObjValueAny = route.params;// 跳转参数 params
    const routeQuery: ObjValueAny = route.query;// 跳转参数 query
    const isEdit = ref<boolean>(routeQuery.id && !routeQuery.same);// 编辑

    // 显示页面
    let showPage = ref<boolean>(false);
    onMounted(() => {
        setRouteName();
        getLevelList();
        getMemberGroups();
        getPreviewShopInfo(_mallStore.mallDetailSetting);
        if (routeQuery.id) {
            showLoading();
            getDetail();
        } else {
            showPage.value = true;
            if (isShopCoupon.value) {
                getShopDataList();
            }
        }
    })

    const getPreviewShopInfo = (row: ObjValueAny) => {
        ruleForm.shopLogo = row.logo || '';
        ruleForm.shopName = row.name || '';
        ruleForm.shopAddress = row.address || '';
    }
    // 闪购优惠券
    const isFlashCoupon = computed(() => {
        return +routeParams.group_id === isFlashCouponGroupId;
    });
    // 停车优惠券
    const isParkCoupon = computed(() => {
        return +routeParams.group_id === isParkCouponGroupId;
    });
    // 店铺优惠券
    const isShopCoupon = computed(() => {
        return +routeParams.origin === isOriginShopCoupon;
    })

    // 修改面包屑标题
    const originTitle = ref<string>('');
    const setRouteName = () => {
        let _title: string;
        const _beforeTitle: string = isEdit.value ? '编辑' : '新增';
        originTitle.value = isShopCoupon.value ? '店铺' : '商场';
        if (isParkCoupon.value) {
            _title = `${_beforeTitle}停车券`;
        } else {
            _title = `${_beforeTitle}${originTitle.value}券`;
        }
        _layoutStore.editBreadcrumbName(route.name as string, _title);
    }
    // 优惠券详情
    let disabledDate = ref();// 有效期 禁用日期
    let activityDisabled = ref<boolean>(false);// 编辑 禁用
    const getDetail = () => {
        return new Promise(resolve => {
            getRestfulMallV2CouponDetail(+routeQuery.id).then((resp: ObjValueAny) => {
                if (resp.code === 200) {
                    const { data }: ObjValueAny = resp;
                    activityDisabled.value = !!([0, 1, 4].includes(data.status) && data.published_at && isEdit.value) && !isSuperManage.value;
                    // 赋值
                    for (let key in submitData) {
                        if (submitData.hasOwnProperty(key) && data.hasOwnProperty(key)) {
                            ruleForm[key] = data[key];
                        }
                    }
                    ruleForm.head_img = data.imgs[0];
                    // 优惠券所属活动
                    if (data.campaign?.id) {
                        ruleForm.campaign_id = data.campaign.id;
                        ruleForm.campaignConfig = data.campaign;
                    }
                    // 有效期
                    if (data.start_at) {
                        ruleForm.period_type = 1;
                        ruleForm.periodDateRange = [data.start_at, data.end_at];
                    } else {
                        ruleForm.period_type = 2;
                        ruleForm.valid_period = data.valid_period;
                    }
                    // 会员领取权限
                    getBuyLimitRuleForm(data, ruleForm);
                    // 是否限领
                    ruleForm.receiveRule = data.receive_rule > 0;
                    // 券类型
                    getCouponTypes(data.channel);
                    // 店铺券 选择店铺
                    if (data.origin === isOriginShopCoupon) {
                        ruleForm.groupIds = data.group_ids[0];
                    }
                    // 发放方式
                    if (data.times?.length) {
                        // 多时段发放
                        ruleForm.timesRadio = 2;
                        ruleForm.times = data.times;
                    } else {
                        // 持续发放
                        ruleForm.timesRadio = 1;
                        ruleForm.times = [{
                            start_at: data.timing_published_at,
                            end_at: data.timing_unpublished_at,
                            left_num: data.left_num || data.num,
                            num: data.num,
                        }]
                    }
                    const nowParse = getDateParse();
                    ruleForm.times = ruleForm.times.map((row: ObjValueAny) => {
                        const disStart = activityDisabled.value && nowParse >= getDateParse(row.start_at.slice(0, 16));// 禁用开始时间之前
                        const disabled = activityDisabled.value && nowParse >= getDateParse(row.end_at.slice(0, 16));// 禁用日期选择器
                        const isLeftNum = row.hasOwnProperty('left_num');
                        const timeRow: ObjValueAny = {
                            disStart,
                            disabled,
                            editNum: isEdit.value && isLeftNum ? row.left_num : row.num,
                            date: [row.start_at, row.end_at],
                            hideRemove: true,
                            disabledDate: disStart && !disabled ? disBeforeDay(row.start_at) : null,
                        }
                        if (isLeftNum) {
                            timeRow.left_num = row.left_num;
                        }
                        return timeRow
                    });
                    // 预热时间
                    ruleForm.advanceNotice = getLotteryPeriod(data.advance_notice || 0);
                    // 优惠补贴比例
                    ruleForm.mall_subsidy_rate = (+data.mall_subsidy_rate).toFixed(1);

                    const hasGroupIds: boolean = !!data.group_ids?.length;// 是否选择店铺
                    const hasSendShopIds: boolean = !!data.send_shop_ids?.length;// 是否选择权限店铺
                    const hasItemIds: boolean = !!data.item_ids?.length;// 是否选择商品

                    const promiseAllApi: ObjValueAny[] = [];
                    // 店铺券
                    if (isShopCoupon.value) {
                        if (hasGroupIds) {
                            promiseAllApi.push(getShopDetail(data.group_ids[0]));
                        }
                        if (hasItemIds) {
                            promiseAllApi.push(getItemDataList(data.group_ids[0]));
                        }
                    }
                    if (hasGroupIds || hasSendShopIds) {
                        promiseAllApi.push(getShopDataList());
                    }
                    Promise.all(promiseAllApi).then(() => {
                        if (isShopCoupon.value) {
                            getPreviewShopInfo(shopDetail);
                            if (hasSendShopIds) {
                                ShopModelRef.value.refGetModelValue(shopListData.value, data[sendShopKeyName.value], sendShopKeyName.value);
                            }
                            if (hasItemIds) {
                                ItemModelRef.value.refGetModelValue(itemListData, data.item_ids);
                            }
                        } else {
                            ShopModelRef.value.refGetModelValue(shopListData.value, data[groupShopKeyName.value], groupShopKeyName.value);
                        }
                        storeRuleForm = JSON.parse(JSON.stringify(ruleForm));
                        showPage.value = true;
                        hideLoading();
                    })
                } else {
                    ElMessage.error(`getRestfulMallV2CouponDetail：${resp.msg}`);
                }
            })
        })
    }

    // 缓存券详情
    let storeRuleForm: ObjValueAny = {};
    const publicSubmitData: ObjValueAny = {
        origin: 1, // 1:商场券 2:店铺券
        purpose: 1,
        sub_type: '',
        head_img: '',
        name: '',
        soule: '',
        minus: '',
        off: '',
        start_at: '',
        end_at: '',
        valid_period: '',
        participation_rules: 0,
        use_limit: 0,
        use_limit_num: '',
        level_ids: [],
        receive_rule: '',
        receive_limit: '',
        premium_exclusive: 2,
        sendable: 0,
        send_shop_ids: [],
        describe: '',
        remark: '',
    }
    // 停车券
    const parkSubmitData: ObjValueAny = {
        free_park_hour: '',
        channel: 2,
        group_id: routeParams.group_id,
        ...publicSubmitData
    }
    // 优惠券 表单字段
    const flashSubmitData: ObjValueAny = {
        subhead: '',
        campaign_id: '',
        platform: 3,
        channel: '',
        amount_limit: 0,
        amount_over: '',
        over: '',
        purchase: '',
        demand: '',
        arrive: '',
        group_ids: [],
        all_item: '',
        item_ids: [],
        deny_group_ids: [],
        item_refundable: '',
        coupon_refundable: '',
        detail_imgs: [],
        mall_subsidy_rate: 0,
        ...publicSubmitData
    };
    let ruleForm = reactive<ObjValueAny>({
        campaignConfig: {},
        period_type: '',
        periodDateRange: [],
        levelIds: [],
        levelIdsChecked: false,
        crowdTypeChecked: false,
        crowdType: '',
        denyGroups: {},
        receiveRule: false,
        groupId: '',
        groupName: '',
        itemName: '',
        sendShopName: '',
        timesRadio: '',
        advanceNotice: {},
        times: [],
        editNum: '',
    });
    let submitData = reactive<ObjValueAny>({});
    // 重置 人群包
    const resetDenyGroups = () => {
        ruleForm.denyGroups = { id: '', count: 0, name: '' };
    }
    // 重置 预热时间
    const resetAdvanceNotice = () => {
        ruleForm.advanceNotice = { value1: '', value2: '', value3: '' };
    }
    const initSubmitFormData = () => {
        submitData = isParkCoupon.value ? parkSubmitData : flashSubmitData;
        ruleForm = Object.assign(ruleForm, submitData);
    }
    const initRuleForm = () => {
        resetDenyGroups();
        resetAdvanceNotice();
    }
    initSubmitFormData();
    initRuleForm();

    const radioPurpose = reactive<TypeFilters.filter[]>(CouponPurpose());// 券用途
    const radioPurposeParaphrase = reactive<ObjValueNum>(getFiltersDictParaphrase(radioPurpose));// 券用途
    const couponScanCodeSubTypes = reactive<TypeFilters.filter[]>(FCouponScanCodeSubTypes);// 扫码发券 二级选项

    // 切换券用途 部分字段显示/隐藏
    const showFormItem = computed(() => {
        return getShowFormItem(ruleForm);
    });
    // 选择券用途 =============================================
    const radioChangePurpose = () => {
        if (ruleForm.purpose === radioPurposeParaphrase.saoMaFaQuan) {
            ruleForm.sub_type = 2;
        } else if (ruleForm.purpose === radioPurposeParaphrase.huiYuanDengJiLi) {
            ruleForm.sub_type = 4;
        } else {
            ruleForm.sub_type = '';
        }
        // 清空 优惠券所属活动
        if (!showFormItem.value.campaigns) {
            ruleForm.campaign_id = '';
            ruleForm.campaignConfig = {};
        }
        // 清空 会员领取权限
        if (!showFormItem.value.buyLimit) {
            ruleForm.participation_rules = 0;
            resetBuyLimit(ruleForm);
        }
        // 清空 自定义发券权限
        if (!showFormItem.value.sendShop) {
            ruleForm.sendable = 0;
            switchSendAble();
        }
        // 清空 分发方式
        ruleForm.timesRadio = '';
        if (!showFormItem.value.sendWay) {
            ruleForm.times = [];
        } else {
            // 只显示 持续发放
            if (showFormItem.value.sustain) {
                ruleForm.timesRadio = 1;
                changeTimesRadio();
            }
        }
        // 清空 预热时间
        if (!showFormItem.value.advanceNotice) {
            resetAdvanceNotice();
        }
    }
    // 选择 优惠券所属活动 =============================================
    let campaignDialog = ref<boolean>(false);// 优惠券所属活动弹窗
    const showCampaignDialog = () => {
        campaignDialog.value = true;
    }
    const changeCampaign = (id: number | string, row: ObjValueAny | null) => {
        ruleForm.campaign_id = id;
        ruleForm.campaignConfig = row || {};
    }
    // 删除 优惠券所属活动
    const removeCampaign = () => {
        ruleForm.campaign_id = '';
        ruleForm.campaignConfig = {};
    }
    // 适用范围/券类型 =============================================
    // 现金券
    const isCashCoupon = computed(() => {
        return ruleForm.soule === couponTypesParaphrase.value.xianJin
    });
    // 适用范围 =============================================
    const couponChannel = reactive<TypeFilters.filter[]>(FCouponChannel);
    const couponChannelParaphrase = reactive<ObjValueNum>(FCouponChannelParaphrase);
    // 线下券
    const isOfflineCoupon = computed(() => {
        return ruleForm.channel === couponChannelParaphrase.xianXia
    });
    // 线上券
    const isOnLineCoupon = computed(() => {
        return ruleForm.channel === couponChannelParaphrase.xianShang
    });
    const radioChangeChannel = (value: number) => {
        resetCouponTypes(value);
    }
    // 券类型 =============================================
    const typesTips = reactive<ObjValueStr>({
        1: '*满减券：如“满100减10',
        2: '*折扣券：如“买2件打8折”，折扣数请输入0-10之间的数字，8.5折即原价的85%',
        3: '*礼品券：如“礼品券/精美礼品一份”',
        4: '*现金券：如“10元/无门槛使用”',
        5: '*抵用券：如“49元/可抵100元”',
    });
    const parkTypesTips = reactive<ObjValueStr>({
        2: '*折扣券：支付时依据设置折扣进行扣减，如：应付10元，使用8.8折券，实付8.8元',
        4: '*现金券：支付车费时直接扣减设置的金额，如：应付10元，使用2元现金券，实付8元',
        7: '*时长券：固定时长内停车免费，超出设定时长部分正常计费，如：每小时收费2元，停车4小时，应付8元，使用3小时免费券，实付2元',
    });
    let couponTypes = ref<TypeFilters.filter[]>(FCouponTypes);// 优惠券类型
    let couponTypesParaphrase = ref<ObjValueNum>(FCouponTypesParaphrase);// 优惠券类型
    let parkCouponTypes = ref<TypeFilters.filter[]>(FParkCouponTypes);// 停车券类型
    // 切换券 类型
    const radioChangeTypes = () => {
        ruleForm.amount_limit = 0;
        switchAmountLimit(ruleForm.amount_limit);
        ruleForm.use_limit = 0;
        switchUseLimitNum(ruleForm.use_limit);
        emptyTypesValue();
        nextTick(() => {
            ruleFormRef.value.validateField('typeValue', () => {
            })
        });
    }
    // 重置券类型 value:适用范围
    const resetCouponTypes = (value: number) => {
        emptyTypesValue();
        ruleForm.soule = couponTypes.value[0].value;
        getCouponTypes(value);
    }
    const getCouponTypes = (value: number) => {
        if (value !== couponChannelParaphrase.xianXia) {
            // 非线下券 不显示礼品券
            couponTypes.value = getExcludeFilters(FCouponTypes, [couponChannelParaphrase.xianShangXianXia]);
        } else {
            couponTypes.value = FCouponTypes;
        }
    }
    // 清空 券类型 条件
    const emptyTypesValue = () => {
        ruleForm.over = '';
        ruleForm.minus = '';
        ruleForm.purchase = '';
        ruleForm.off = '';
        ruleForm.demand = '';
        ruleForm.arrive = '';
        if (isShopCoupon.value) {
            ruleForm.all_item = '';
            clearItems();
        }
    }
    // 使用门槛
    const switchAmountLimit = (value: number) => {
        ruleForm.amount_over = '';
        if (value === 1) {
            nextTick(() => {
                ruleFormRef.value.validateField('amount_over', () => {
                })
            })
        }
    }
    // 单笔订单使用上限
    const switchUseLimitNum = (value: number) => {
        ruleForm.use_limit_num = '';
        if (value === 1) {
            nextTick(() => {
                ruleFormRef.value.validateField('use_limit_num', () => {
                })
            })
        }
    }
    // 有效期 ======================================================
    const changeDateRangeValidPeriod = () => {
        ruleForm.validPeriodText = getCouponValidPeriodDetail({
            period_type: ruleForm.period_type,
            start_at: ruleForm.periodDateRange[0] || '',
            end_at: ruleForm.periodDateRange[1] || '',
            valid_period: ruleForm.valid_period,
        });
        nextTick(() => {
            if (ruleForm.period_type === 1) {
                ruleFormRef.value.validateField('periodDateRange', () => {
                })
            }
            if (ruleForm.period_type === 2) {
                ruleFormRef.value.validateField('valid_period', () => {
                })
            }
        })
    }
    const changeBuyLimit = () => {
        ruleFormRef.value.validateField('participation_rules', () => {
        })
        if (ruleForm.levelIdsChecked) {
            ruleFormRef.value.validateField('levelIds', () => {
            })
        }
        if (ruleForm.crowdTypeChecked) {
            ruleFormRef.value.validateField('denyGroups', () => {
            })
        }
    }
    // 是否限领 =============================================
    const receiveRuleOptions = reactive(FReceiveRules);
    const switchReceiveRule = (bool: boolean) => {
        ruleForm.receive_rule = '';
        ruleForm.receive_limit = '';
        if (bool) {
            ruleForm.receive_rule = receiveRuleOptions[0].value;
            nextTick(() => {
                ruleFormRef.value.validateField('receive_limit', () => {
                })
            })
        }
        getReceiveText();
    }
    const getReceiveText = () => {
        if (+ruleForm.receive_rule > 0) {
            ruleForm.receiveLimit = FReceiveRulesLabel[ruleForm.receive_rule] + ruleForm.receive_limit + '张';
        } else {
            ruleForm.receiveLimit = '不限领';
        }
    }

    // 商场券 店铺选择 ==========================================================================
    let storeShopIds = ref<number[]>([]);
    let groupShopKeyName = ref<string>('group_ids');// 选择店铺 key值
    let sendShopKeyName = ref<string>('send_shop_ids');// 自定义发券权限 key值
    let shopKeyName = ref<string>('');
    // 选择店铺
    const showGroupShopDialog = () => {
        shopKeyName.value = groupShopKeyName.value;
        showShopDialog();
    }
    // 自定义发券权限
    const showSendShopDialog = () => {
        shopKeyName.value = sendShopKeyName.value;
        showShopDialog();
    }
    // 显示店铺弹窗
    let shopDialog = ref<boolean>(false);// 店铺选择弹窗
    const showShopDialog = () => {
        shopDialog.value = true;
        storeShopIds.value = ruleForm[shopKeyName.value]
    }
    // 选择店铺
    const changeShops = (ids: number[], text: string, list: ObjValueAny[], key: string) => {
        ruleForm[key] = ids;
        setShopNames(key, text);
    }
    // 清空店铺
    const clearShops = (key: string) => {
        ruleForm[key] = [];
        setShopNames(key);
    }
    // 显示店铺名称
    const setShopNames = (key: string, text: string = '') => {
        if (key === groupShopKeyName.value) {
            ruleForm.groupName = text;
        }
        if (key === sendShopKeyName.value) {
            ruleForm.sendShopName = text;
        }
    }

    // 自定义发券权限 开关
    const switchSendAble = () => {
        ruleForm[sendShopKeyName.value] = [];
        setShopNames(sendShopKeyName.value);
        if (ruleForm.sendable === 1) {
            nextTick(() => {
                ruleFormRef.value.validateField('sendShopName', () => {
                })
            })
        }
    }

    // 选择店铺
    // 显示 商品选择 (优惠券架)
    const showAllItems = computed(() => {
        return isShopCoupon.value && ruleForm.groupIds && ruleForm.channel && ruleForm.channel !== couponChannelParaphrase.xianXia;
    });
    const changeSelectShop = () => {
        ruleForm.all_item = 0;
        changeAllItems();
        if (showAllItems.value) {
            nextTick(() => {
                ruleFormRef.value.validateField('all_item', () => {
                })
            })
        }
        getShopResp();
    }
    const getShopResp = () => {
        getApiShopDetail({ shop_id: ruleForm.groupIds }).then((resp: ObjValueAny) => {
            getPreviewShopInfo(resp.data);
        })
    }

    // 选择店内商品
    let itemDialog = ref<boolean>(false);
    const showItemDialog = () => {
        itemDialog.value = true;
    }
    const changeItems = (ids: number[], text: string) => {
        ruleForm.item_ids = ids;
        ruleForm.itemName = text;
    }
    // 清空商品
    const changeAllItems = () => {
        clearItems();
        itemNameValidateField();
    }
    const clearItems = () => {
        ruleForm.item_ids = [];
        ruleForm.itemName = '';
    }
    const itemNameValidateField = () => {
        if (ruleForm.all_item === 0) {
            nextTick(() => {
                ruleFormRef.value.validateField('itemName', () => {
                })
            })
        }
    }

    // 发放方式 =============================================
    let timesKeys = 1;
    const timesValue = () => {
        return {
            key: timesKeys++,
            date: [],
            editNum: '',
            disStart: false
        }
    }
    const changeTimesRadio = () => {
        ruleForm.times = [timesValue()];
        initTimesValidator(0);
    }
    const addTimes = () => {
        ruleForm.times.push(timesValue());
        initTimesValidator(ruleForm.times.length - 1);
    }
    const removeTimes = (i: number) => {
        ruleForm.times.splice(i, 1);
        for (let j = 0; j < ruleForm.times.length; j++) {
            if (j >= i) initTimesValidator(j);
        }
    }
    const initTimesValidator = (i: number) => {
        nextTick(() => {
            if (!showFormItem.value.sustain) {
                ruleFormRef.value.validateField('times.' + i + '.date', () => {
                })
            }
            ruleFormRef.value.validateField('times.' + i + '.editNum', () => {
            })
        })
    }

    // 使用优惠的订单 =============================================
    const changeItemRefundable = () => {
        ruleForm.coupon_refundable = '';
        if (ruleForm.item_refundable === 1) {
            ruleFormRef.value.validateField('coupon_refundable', () => {
            })
        }
    }

    // 输入商场补贴 计算 店铺补贴 =============================================
    const shopSubsidyRate = computed(() => {
        return (Math.round((100 - ruleForm.mall_subsidy_rate) * 100) / 100).toFixed(1);
    });

    // 表单验证 ================================================================================
    const validatorFormEmpty = (message: string) => {
        return (rule: ObjValueAny, value: string | number, callback: Function) => {
            if (subStatus && value !== 0 && !value) {
                return callback(new Error(message))
            }
            callback()
        }
    };
    // 券类型及使用条件
    const validatorTypeValue = (rule: ObjValueAny, value: string | number, callback: Function) => {
        if (subStatus) {
            const prompt = '请输入使用券类型及使用条件';
            if (ruleForm.soule === couponTypesParaphrase.value.manJian && (!ruleForm.over || !ruleForm.minus)) {
                return callback(new Error(prompt));
            }
            if (ruleForm.soule === couponTypesParaphrase.value.zheKou) {
                if ((isFlashCoupon.value && !ruleForm.purchase) || !ruleForm.off) {
                    return callback(new Error(prompt));
                }
            }
            if (ruleForm.soule === couponTypesParaphrase.value.liPin && (!ruleForm.demand)) {
                return callback(new Error(prompt));
            }
            if (isCashCoupon.value) {
                if ((isFlashCoupon.value && !ruleForm.demand) || !ruleForm.minus) {
                    return callback(new Error(prompt));
                }
            }
            if (ruleForm.soule === couponTypesParaphrase.value.diYong && (!ruleForm.arrive || !ruleForm.over)) {
                return callback(new Error(prompt));
            }
            if (ruleForm.soule === couponTypesParaphrase.value.shiChang && !ruleForm.free_park_hour) {
                return callback(new Error(prompt));
            }
        }
        callback()
    };
    // 使用门槛 验证
    const validatorAmountOver = (rule: ObjValueAny, value: string | number, callback: Function) => {
        if (subStatus && isCashCoupon.value && ruleForm.amount_limit && !value) {
            return callback(new Error('请输入使用门槛'));
        }
        callback()
    }
    // 单笔订单使用上限 验证
    const validatorUseLimitNum = (rule: ObjValueAny, value: string | number, callback: Function) => {
        if (subStatus && isCashCoupon.value && ruleForm.use_limit) {
            if (!value) {
                return callback(new Error('请输入单笔订单使用上限'));
            }
            if (+value <= 0) {
                return callback(new Error('单笔订单使用上限须大于0'));
            }
        }
        callback()
    }
    // 固定有效期
    const validatorPeriodDateRange = (rule: ObjValueAny, value: string[], callback: Function) => {
        if (subStatus) {
            validatorDateRangeRule(value, callback, {
                storeEnd: storeRuleForm.verify_end_day,
            });
        }
    }
    // 浮动有效期
    const validatorValidPeriod = (rule: ObjValueAny, value: number, callback: Function) => {
        if (subStatus) {
            validatorValidPeriodRule(value, callback, { storeValidPeriod: storeRuleForm.valid_period });
        }
    }
    // 会员领取权限
    const validatorLevelLimit = (rule: ObjValueAny, value: number, callback: Function) => {
        if (subStatus) {
            buyLimitLevelLimitRule(value, callback, ruleForm, '领取');
        }
    };
    // 会员等级 验证
    const validatorLevelIds = (rule: ObjValueAny, value: ObjValueAny[], callback: Function) => {
        if (subStatus) {
            buyLimitLevelIdsRule(value, callback, ruleForm);
        }
    };
    // 人群包 验证
    const validatorDenyGroups = (rule: ObjValueAny, value: ObjValueAny, callback: Function) => {
        if (subStatus) {
            buyLimitDenyGroupsRule(value, callback, ruleForm);
        }
    };
    // 是否限领
    const validatorReceiveLimit = (rule: ObjValueAny, value: number, callback: Function) => {
        if (subStatus) {
            if (!value && value !== 0) {
                return callback(new Error('请输入限领数量'));
            }
            if (+value <= 0) {
                return callback(new Error('限领数量须大于0'));
            }
        }
        callback()
    };
    // 发放方式
    const validatorTimesDate = (rule: ObjValueAny, value: string[], callback: Function, i: number) => {
        if (subStatus) {
            if (!value.length) {
                return callback(new Error('请选择分发时段'));
            }
            const endParse = getDateParse(value[1]);
            if (activityDisabled.value) {
                const timeRow = ruleForm.times[i];
                if (timeRow.disStart && !timeRow.disabled) {
                    const _endEnd: string = storeRuleForm.times && storeRuleForm.times[i] ? storeRuleForm.times[i].end_at : null;
                    if (_endEnd) {
                        const storeEndParse = getDateParse(_endEnd);
                        if (endParse < storeEndParse) {
                            return callback(new Error('有效时长不可缩短'));
                        }
                    }
                }
            } else {
                const nowParse = getDateParse();
                if (endParse < nowParse) {
                    return callback(new Error('结束时间需大于当前时间'));
                }
            }
        }
        callback()
    };
    const validatorTimesNum = (rule: ObjValueAny, value: number, callback: Function, i: number) => {
        if (subStatus) {
            if (!value) {
                return callback(new Error('请输入发放张数'));
            }
            if (value < 1) {
                return callback(new Error('持续发放张数需大于0'));
            }
            const timeRow = ruleForm.times[i];
            if (activityDisabled.value && timeRow.disStart) {
                if (+value < timeRow.left_num) {
                    return callback(new Error('发放张数不可减少'));
                }
            }
        }
        callback()
    };
    // 优惠补贴比例
    const validatorMallSubsidyRate = (rule: ObjValueAny, value: number | string, callback: Function) => {
        if (subStatus) {
            if (!value && value !== 0) {
                return callback(new Error('请输入优惠方补贴'));
            }
            if (+value > 100) {
                return callback(new Error('优惠方补贴不得大于100%'));
            }
        }
        callback()
    };
    // 表单验证 字段
    const ruleFormRef = ref();
    let subStatus: boolean = false;
    const rules = reactive<ObjValueAny>({
        head_img: [{ required: true, validator: validatorFormEmpty('请上传头图'), trigger: 'change' }],
        name: [{ required: true, validator: validatorFormEmpty('请输入优惠券标题'), trigger: 'change' }],
        channel: [{ required: true, validator: validatorFormEmpty('请选择适用范围'), trigger: 'change' }],
        soule: [{ required: true, validator: validatorFormEmpty('请选择券类型'), trigger: 'change' }],
        typeValue: [{ required: true, validator: validatorTypeValue, trigger: 'change' }],
        amount_over: [{ required: true, validator: validatorAmountOver, trigger: 'change' }],
        use_limit_num: [{ required: true, validator: validatorUseLimitNum, trigger: 'change' }],
        period_type: [{ required: true, validator: validatorFormEmpty('请选择有效期类型'), trigger: 'change' }],
        periodDateRange: [{ required: true, validator: validatorPeriodDateRange, trigger: 'change' }],
        valid_period: [{ required: true, validator: validatorValidPeriod, trigger: 'change' }],
        participation_rules: [{ required: true, validator: validatorLevelLimit, trigger: 'change' }],
        levelIds: [{ required: true, validator: validatorLevelIds, trigger: 'change' }],
        denyGroups: [{ required: true, validator: validatorDenyGroups, trigger: 'change' }],
        receive_limit: [{ required: true, validator: validatorReceiveLimit, trigger: 'change' }],
        groupName: [{ required: true, validator: validatorFormEmpty('请选择店铺'), trigger: 'change' }],
        sendShopName: [{ required: true, validator: validatorFormEmpty('请选择可发券店铺'), trigger: 'change' }],
        all_item: [{ required: true, validator: validatorFormEmpty('请选择适用商品'), trigger: 'change' }],
        describe: [{ required: true, validator: validatorFormEmpty('请输入使用须知'), trigger: 'change' }],
        item_refundable: [{ required: true, validator: validatorFormEmpty('请选择使用优惠的商品'), trigger: 'change' }],
        coupon_refundable: [{ required: true, validator: validatorFormEmpty('请选择使用优惠的商品全退后'), trigger: 'change' }],
        timesRadio: [{ required: true, validator: validatorFormEmpty('请选择发放方式'), trigger: 'change' }],
        mall_subsidy_rate: [{ required: true, validator: validatorMallSubsidyRate, trigger: 'change' }],
    });

    const submitForm = (formEl: any) => {
        subStatus = true;
        if (!formEl) return;
        formEl.validate((valid: boolean, fields: ObjValueAny) => {
            if (valid) {
                console.log('submit!');
                if (isEdit.value) {
                    showDialogPrompt();
                } else {
                    onSave();
                }
            } else {
                console.log('error submit!', fields);
                // 跳转到第一个未通过的
                // const keys = Object.keys(fields)
                // ruleFormRef.value.scrollToField(keys[0])
            }
        });
    }
    let subLoading = ref<boolean>(false);// 保存中
    const resetLoading = () => {
        subLoading.value = false;
    }

    let dialogPrompt = ref<boolean>(false);
    const showDialogPrompt = () => {
        dialogPrompt.value = true;
    }
    const closeDialogPrompt = () => {
        dialogPrompt.value = false;
    }

    const onSave = () => {

    }

    // 店铺列表
    const ShopModelRef = ref();// 绑定选择店铺dom ref
    let shopListData = ref<ObjValueAny[]>([]);// 店铺列表
    const getShopDataList = async () => {
        shopListData.value = await ShopModelRef.value.getStoreDataList();
    }
    // 店铺详情
    let shopDetail: ObjValueAny = {};
    const getShopDetail = async (id: number) => {
        const resp: ObjValueAny = await getApiShopDetail({ shop_id: id });
        shopDetail = resp.data;
    }
    // 商品列表
    const ItemModelRef = ref();// 绑定商品列表dom ref
    let itemListData: ObjValueAny[] = [];// 店铺列表
    const getItemDataList = async (id: number) => {
        itemListData = await ItemModelRef.value.getStoreDataList({ shop_id: id });
    }
    // 获取会员等级列表
    let levelOptions = ref<TypeFilters.filterApi[]>([]);
    const getLevelList = async () => {
        levelOptions.value = await getRestfulMallLevelsFilter();
    }
    // 人群包 列表
    let memberGroupOptions = ref<TypeFilters.filterApi[]>([]);
    const getMemberGroups = async () => {
        memberGroupOptions.value = await getRestfulMallMemberGroupsFilter();
    }
</script>

<style scoped lang="scss">
    /* 表单报错文案 不换行 */
    :deep(.el-form-item__error) {
        white-space: nowrap;
    }
</style>